//
//  AdditionalFreeItemsPricing.m
//  CodeKatas
//
//  Created by Viktor Lazarevich on 28-Feb-10.
//  Copyright 2010 Home. All rights reserved.
//

#import "AdditionalFreeItemsPricing.h"


@implementation AdditionalFreeItemsPricing

- (id)initWithPrice:(Money)price {
	Quantity pQuantity = MakeQuantityFromPieces(1);
	Quantity fQuantity = MakeQuantityFromPieces(0);
	return [self initWithPrice:price paidQuantity:pQuantity freeQuantity:fQuantity];
}

- (id)initWithPrice:(Money)price paidQuantity:(Quantity)pQuantity freeQuantity:(Quantity)fQuantity {
	if ((pQuantity.quantity <= 0.0) || (fQuantity.quantity < 0.0)) {
		[self release];
		return nil;
	}
	
	if (self = [super initWithPrice:price]) {
		paidQuantity = pQuantity;
		freeQuantity = fQuantity;
	}
		
	return self;
}

- (Money)getPriceFor:(Quantity)quantity {
	Quantity fullCycle = SumQuantity(paidQuantity, freeQuantity);
	int cycles = floor(DivideQuantity(quantity, fullCycle));
	Quantity cyclesQuantity = MultiplyQuantityBy(fullCycle, cycles);

	Quantity rest = SubtractQuantity(quantity, cyclesQuantity);
	Quantity paidRest;
	if (rest.quantity < paidQuantity.quantity)
		paidRest = rest;
	else
		paidRest = paidQuantity;
	
	Quantity totalPaidQuantity = SumQuantity(MultiplyQuantityBy(paidQuantity, cycles), paidRest);
	return Multiply(pricePerOne, totalPaidQuantity);
}
@end
